package com.gfdd.tea.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gfdd.tea.common.R;
import com.gfdd.tea.dto.OrdersDto;
import com.gfdd.tea.pojo.*;
import com.gfdd.tea.service.*;
import com.gfdd.tea.utlis.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/orders")
@Slf4j
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private TeasService teasService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;

    /**
     * 支付
     * @param map
     * @param userId
     * @return
     */
    @PostMapping("/pay")
    public R<String> pay(@RequestBody Map<String, Object> map, Long userId) {
        Integer addressBookId = (Integer) map.get("addressBookId");
        Integer teaId = (Integer) map.get("teaId");
        User user = userService.getById(userId);
        List<Integer> data = (List<Integer>) map.get("shoppingCartId");
        if (data != null) {
            log.info("在购物车发起支付");
            List<Long> shoppingCartId = JSONArray.parseArray(data.toString(), Long.class);
            LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ShoppingCart::getUserId, userId);
            wrapper.in(ShoppingCart::getId, shoppingCartId);
            List<ShoppingCart> shoppingCartList = shoppingCartService.list(wrapper);
            if (shoppingCartList.isEmpty()||shoppingCartList.size()==0){
                return R.error("购物车为空为无法下单!!!");
            }
            long orderId = IdWorker.getId();
            AtomicInteger amount = new AtomicInteger(0);
            List<OrderDetail> orderDetails = shoppingCartList.stream().map(item -> {
                Teas byId = teasService.getById(item.getTeaId());
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setTeaId(byId.getId());
                orderDetail.setImage(byId.getImageFile());
                orderDetail.setOrderId(orderId);
                orderDetail.setNumber(item.getNumber());
                orderDetail.setName(byId.getTeaName());
                orderDetail.setAmount(new BigDecimal((new BigDecimal(byId.getSalePrice())).multiply(new BigDecimal(orderDetail.getNumber())).intValue()));
                amount.addAndGet((new BigDecimal(byId.getSalePrice())).multiply(new BigDecimal(orderDetail.getNumber())).intValue());
                orderDetail.setAmount(new BigDecimal(amount.get()));
                return orderDetail;
            }).collect(Collectors.toList());
            //向订单表插入数据，一条数据
            Orders orders = new Orders();
            orders.setNumber(String.valueOf(orderId));
            orders.setId(orderId);
            orders.setOrderTime(DateUtils.DateFormat(new Date()));
            orders.setCheckoutTime(DateUtils.DateFormat(new Date()));
            orders.setUserId(userId);
            orders.setAddressBookId(addressBookId.longValue());
            orders.setAddress("广東省广州市从化区太平镇广州软件学院");
            orders.setPhone("18208020888");
            orders.setConsignee("小黑");
            orders.setStatus(2);
            orders.setAmount(new BigDecimal(amount.get()));//计算总金额
            orders.setUserName(user.getNickName());
            ordersService.save(orders);
            //向订单明细插入数据，多条数据
            orderDetailService.saveBatch(orderDetails);
            //清空购物车
            shoppingCartService.removeByIds(shoppingCartId);
            return  R.success("下单成功");
        } else  {
            log.info("在商品页发起支付");
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setNumber((Integer) map.get("number"));
            Teas byId = teasService.getById(teaId.longValue());
            Long salePrice = byId.getSalePrice();
            //计算金额
            AtomicInteger amount = new AtomicInteger(0);
            amount.addAndGet((new BigDecimal(salePrice)).multiply(new BigDecimal(orderDetail.getNumber())).intValue());
            orderDetail.setAmount(new BigDecimal(amount.get()));
            //生成订单id
            long id = IdWorker.getId();
            orderDetail.setOrderId(id);
            orderDetail.setImage(byId.getImageFile());
            orderDetail.setTeaId(byId.getId());
            orderDetail.setName(byId.getTeaName());
            //保存订单明细
            orderDetailService.save(orderDetail);
            //将订单生成数据补全
            Orders orders = new Orders();
            orders.setId(id);
            orders.setCheckoutTime(DateUtils.DateFormat(new Date()));
            orders.setAddressBookId(addressBookId.longValue());
            orders.setStatus(2);
            orders.setUserId(userId);
            orders.setAddress("广東省广州市从化区太平镇广州软件学院");
            orders.setPhone("18208020888");
            orders.setConsignee("小黑");
            orders.setAmount(new BigDecimal(amount.get()));
            //保存订单信息
            ordersService.save(orders);
            return R.success("支付成功！");
        }
    }

    /**
     * 获取订单详情
     * @param page
     * @param pageSize
     * @param userId
     * @return
     */
    @GetMapping("/payInfoPage")
    public R<Page<OrdersDto>> userPages(int page, int pageSize,Long userId){
        Page<OrdersDto> pageInfo=new Page<>();
        Page<Orders> ordersPageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId,userId);
        queryWrapper.orderByDesc(Orders::getCheckoutTime);
        ordersService.page(ordersPageInfo ,queryWrapper);
        //将ordersPage中信息拷贝到DtoPage中
        BeanUtils.copyProperties(ordersPageInfo,page,"records");
        List<Orders> records = ordersPageInfo.getRecords();
        List<OrdersDto> ordersDtos = records.stream().map((item -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            Long orderId = item.getId();
            LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderDetail::getOrderId, orderId);
            List<OrderDetail> orderDetailList = orderDetailService.list(wrapper);
            ordersDto.setOrderDetails(orderDetailList);
            return ordersDto;
        })).collect(Collectors.toList());
        pageInfo.setRecords(ordersDtos);
        return R.success(pageInfo);
    }
}
